﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;

namespace Infrastructure.CrossCutting.Caching
{
    public class AspNetCache : ILocalCache
    {
        #region Private Methods

        private static Cache GetCache()
        {
            return System.Web.HttpRuntime.Cache;
        }

        #endregion Private Methods

        #region ICache Members

        public object Get(CacheKey cacheKey)
        {
            var cache = GetCache();
            string key = cacheKey.GetCacheKey();
            return cache.Get(key);
        }

        public void Set(CacheItemConfig cacheItemConfig, object value)
        {
            var cache = GetCache();

            string key = cacheItemConfig.CacheKey.GetCacheKey();
            TimeSpan expirationTime = cacheItemConfig.ExpirationTime;

            cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, expirationTime);
        }

        public bool Remove(CacheKey cacheKey)
        {
            var cache = GetCache();
            var value = cache.Remove(cacheKey.GetCacheKey());
            return value != null;
        }

        public void Clear()
        {
            var cache = GetCache();

            var keys = new List<string>();
            var enumerator = cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                keys.Add(enumerator.Key.ToString());
            }

            // delete every key from cache
            foreach (var key in keys)
            {
                cache.Remove(key);
            }
        }

        #endregion ICache Members

    }
}
